package com.yuange.utils.common;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @作者：袁工
 * @时间：2021/9/15 14:19
 */
public class CommonUtil {

    public static void main(String[] args) {
    }

    /**
     * 去除字符串中的\t、\n、\r
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String aa = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            aa = m.replaceAll("");
        }
        return aa;
    }

    /**
     * 判断字符串是否以"{开头或}"结尾
     * @param value
     * @return
     */
    public static Boolean isStartsOrEndWithToStr(String value){
        if (value != null && value.length() != 0){
            if (value.startsWith("\"{") || value.endsWith("}\"")) {
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    /**
     * 将字符串按,切割，然后再按=切割，最后将k-v存入JSON中
     * @param value
     * @return
     */
    public static JSONObject conversionStrToJSON(String value){
        if (value != null && value.length() != 0) {
            JSONObject object = new JSONObject();
            String[] split = value.split(",");
            if (split != null && split.length >= 0){
                String tmpEnd = "";
                for (int i = 0; i < split.length; i++) {
                    String a = split[i];
                    String[] split2 = a.split("=");
                    String trim = split2[0].trim();

                    if (tmpEnd != null && tmpEnd.length() != 0) {
                        if (split2.length == 1){
                            object.put(trim,"");
                        }else if (split2.length == 2){
                            object.put(trim,split2[1]);
                        }
                        String column_constraint_str = object.getString("column_constraint");
                        if (column_constraint_str != null && column_constraint_str.length() != 0){
                            String column_constraint = object.getString("column_constraint")+","+tmpEnd;
                            object.put("column_constraint",column_constraint);
                            tmpEnd = null;
                        }else {
                            //未遍历至column_constraint
                        }
                    }else {
                        if (trim.endsWith(")")){
                            tmpEnd = trim;
                            String column_constraint_str = object.getString("column_constraint");
                            if (column_constraint_str != null && column_constraint_str.length() != 0){
                                String column_constraint = object.getString("column_constraint")+","+tmpEnd;
                                object.put("column_constraint",column_constraint);
                                tmpEnd = null;
                            }else {
                                //未遍历至column_constraint
                            }
                        }else {
                            if (split2.length == 1){
                                object.put(trim,"");
                            }else if (split2.length == 2){
                                object.put(trim,split2[1]);
                            }
                        }
                    }
                }
                return object;
            }else {
                return null;
            }
        }else {
            return null;
        }
    }

    /**
     * 去除字符串中以"{开头和}"结尾的符号
     * @param value
     * @return
     */
    public static String filterStrTwo(String value){
        if (value != null && value.length() != 0){
            if (value.startsWith("\"{") || value.endsWith("}\"")) {
                String s = value.replaceAll("\"", "").replaceAll("\\{", "").replaceAll("\\}", "");
                return s;
            }else {
                return value;
            }
        }else {
            return "";
        }
    }

    /**
     * 去除字符串中以"开头和"结尾的"符号
     * @param value
     * @return
     */
    public static String filterStr(String value){
        if (value != null && value.length() != 0){
            if (value.startsWith("\"") || value.endsWith("\"")) {
                String s = value.replaceAll("\"", "");
//                System.out.println("s="+s);
                return s;
            }else {
//                System.out.println("bb="+value);
                if (value.length() > 65535 ){
//                    System.out.println("value="+value.length());
                    return "";
                }else {
                    return value;
                }
            }
        }else {
//            System.out.println("aa="+value);
            return "";
        }
    }

    /**
     * 将JavaBean对象转为JSON对象
     * @param t
     * @return
     */
    public static JSONObject javaBeanConvertToJSON(Object t){
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(t));
        return object;
    }

    /**
     * json数据转换为对象数据
     * @param jsonObject
     * @param cla
     * @param <T>
     * @return
     */
     public static <T> T convertToObj(JSONObject jsonObject, Class<T> cla) {
         if (jsonObject == null) {
             return null;
        }
        Field[] fb = cla.getDeclaredFields();
         T t;
         try {
             t = cla.newInstance();
             for (int j = 0; j < fb.length; j++)
             {
                String fieldName = fb[j].getName();
//                System.out.println("fieldName="+fieldName);
                String fieldNameU = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method method = cla.getMethod("set" + fieldNameU, fb[j].getType());
//                System.out.println(jsonObject);
                method.invoke(t, jsonObject.get(fieldName));
           }
          return t;

      } catch (Exception e) {
            e.printStackTrace();
      }
      return null;
    }

    /*
     * 将结果集转为List
     * */
    public static List<JSONObject> convertList(ResultSet rs) throws SQLException {
        List<JSONObject> list = new ArrayList();
        ResultSetMetaData md = rs.getMetaData();
//        System.out.println(md);
//        System.out.println(md.getColumnName(1));
//        System.out.println(md.getColumnLabel(1));
        int columnCount = md.getColumnCount();
        while (rs.next()) {
            JSONObject obj = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
//                String columnName = md.getColumnName(i);
                String columnLabel = md.getColumnLabel(i);
//                boolean isnullToColumnLabel = columnLabel != null && columnLabel.length() != 0;
//                System.out.println("columnLabel="+columnLabel+",null?==>"+isnullToColumnLabel+",长度="+columnLabel.length());
                obj.put(columnLabel, rs.getObject(i));
            }
            list.add(obj);
        }
        return list;
    }

    /*
    * 二进制转10进制
    * */
    public static int binary2Decimal(String number) {
        return scale2Decimal(number, 2);
    }

    /*
    * 其他进制转十进制
    * */
    public static int scale2Decimal(String number, int scale) {
        checkNumber(number);
        if (2 > scale || scale > 32) {
            throw new IllegalArgumentException("scale is not in range");
        }
        // 不同其他进制转十进制,修改这里即可
        int total = 0;
        String[] ch = number.split("");
        int chLength = ch.length;
        for (int i = 0; i < chLength; i++) {
            total += Integer.valueOf(ch[i]) * Math.pow(scale, chLength - 1 - i);
        }
        return total;
    }

    public static void checkNumber(String number) {
        String regexp = "^\\d+$";
        if (null == number || !number.matches(regexp)) {
            throw new IllegalArgumentException("input is not a number");
        }
    }

    /*
     * 对字符串进行MD5摘要加密，返回结果与MySQL的MD5函数一致
     * 返回值中的字母为小写
     */
    public static String md5(String input) {
        if (null == input) {
            input = "";
        }
        String result = "";
        try {
            // MessageDigest类用于为应用程序提供信息摘要算法的功能，如MD5或SHA算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 获取输入
            md.update(input.getBytes());
            // 获得产出（有符号的哈希值字节数组，包含16个元素）
            byte output[] = md.digest();

            // 32位的加密字符串
            StringBuilder builder = new StringBuilder(32);
            // 下面进行十六进制的转换
            for (int offset = 0; offset < output.length; offset++) {
                // 转变成对应的ASSIC值
                int value = output[offset];
                // 将负数转为正数（最终返回结果是无符号的）
                if (value < 0) {
                    value += 256;
                }
                // 小于16，转为十六进制后只有一个字节，左边追加0来补足2个字节
                if (value < 16) {
                    builder.append("0");
                }
                // 将16位byte[]转换为32位无符号String
                builder.append(Integer.toHexString(value));
            }
            result = builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
    * 生成36位的随机字符串
    * */
    public static String getUUIDTo36(){
        return UUID.randomUUID().toString();
    }

    /*
    * 迭代器转List
    * */
    public static <T> List<T> toList(Iterable<T> it){
        ArrayList<T> list = new ArrayList<>();
        for (T t : it) {
            list.add(t);
        }
        return list;
    }

    /**
     * 将int类型转为二进制
     * @param i 期望转换的整数
     * @param bitNum    期望转换的二进制字符串位数
     * @return
     */
    public static String intToBinary32(Integer i, int bitNum){
        try {
            if (i == null){
                return null;
            }else {
                String binaryStr = Integer.toBinaryString(i);
                while(binaryStr.length() < bitNum){
                    binaryStr = "0"+binaryStr;
                }
                return binaryStr;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
